<template>
  <div class="ant-card">
    <div class="ant-card-head" style="border-bottom: 0">
      <div class="ant-card-head-wrapper">
        <div class="ant-card-head-title">
          {{ isF0401 ? '数据中心关键设备节点传导特性拟合' : '基于能耗传导的数据中心运行仿真' }}
        </div>
      </div>
    </div>
    <div class="ant-card-body" style="padding: 0 24px">
      <a-form
        :labelCol="{ span: 2 }"
        :wrapperCol="{ span: 5 }"
        :form="form"
        :layout="formLayout"
      >
        <a-form-item label="数据中心">
          <a-select
            :getPopupContainer="
                  triggerNode => {
                    return triggerNode.parentNode || document.body;
                  }"
            style="width: 350px"
            v-decorator="['datacenterId', decoratorOptions.datacenterId]"
            @change="handleDatacenterChange"
          >
            <a-select-option
              v-for="(item, index) in datacenterList"
              :key="'type_' + index"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="服务器">
          <a-select
            :getPopupContainer="
                  triggerNode => {
                    return triggerNode.parentNode || document.body;
                  }"
            style="width: 350px"
            v-decorator="['nodeId', decoratorOptions.nodeId]"
          >
            <a-select-option
              v-for="(item, index) in nodeList"
              :key="'type_' + index"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="isF0401" label="空调">
          <a-select
            :getPopupContainer="
            triggerNode => {
              return triggerNode.parentNode || document.body;
            }"
            style="width: 350px"
            v-decorator="['airId', decoratorOptions.airId]"
          >
            <a-select-option
              v-for="(item, index) in airList"
              :key="'type_' + index"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="时间区间">
          <a-range-picker
            class="gw-date-range"
            v-decorator="['rangeTime', rangeConfig]"
            inputReadOnly
            :placeholder="['开始时间', '结束时间']"
            :disabled-date="disabledDate"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
        <a-form-item v-if="!isF0401" label="调整参数">
          <a-select
            :getPopupContainer="
            triggerNode => {
              return triggerNode.parentNode || document.body;
            }"
            style="width: 350px"
            v-decorator="['degree', decoratorOptions.degree]"
          >
            <a-select-option value="2"> 2 </a-select-option>
            <a-select-option value="3"> 3 </a-select-option>
            <a-select-option value="4"> 4 </a-select-option>
            <!-- <a-select-option value="5"> 5 </a-select-option> -->
          </a-select>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 5, offset: 2 }">
          <a-button type="primary" @click="loadData()">
            {{ isF0401 ? '拟合' : '仿真' }}
          </a-button>
        </a-form-item>
      </a-form>
      <div
        id="myChart"
        style="height: 200px"
      ></div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { gPostAction } from "@/api/manage";
import * as echarts from 'echarts';
export default {
  name: "HealthChart",
  props: {
    modelType: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      scatterData: [],
      lineData: [],
      formLayout: "horizontal",
      form: this.$form.createForm(this),
      rangeConfig: {
        rules: [
          { type: "array", required: true, message: "请输入时间区间" },
          { validator: this.validators.datetimeValidator() }
        ],
      },
      timeRange: [],
      xlabel: "",
      ylabel: "",
      nodeList: [],
      airList: [],
      datacenterList: [],
      decoratorOptions: {
        datacenterId: {
          rules: [{ required: true, message: "请选择数据中心" }],
        },
        airId: {
          rules: [{ required: true, message: "请选择设备" }],
        },
        nodeId: {
          rules: [{ required: true, message: "请选择节点" }],
        },
        degree: {
          initialValue: 2,
          rules: [{ required: true, message: "请选择拟合阶数" }],
        },
      },
      isF0401: false,
    };
  },
  mounted() {
    this.isF0401 = (this.modelType === 'f0401');
    this.loadDatacenter(true);
  },
  methods: {
    disabledDate(current) {
      return current && current > moment().endOf('day');
    },
    loadDatacenter() {
      gPostAction("/asset/pageDatacenter", {}).then((res) => {
        if (res.success) {
          const data = res.data;
          if (data && data.list) {
            this.datacenterList = data.list;
            if (data.list && data.list.length) {
              this.form.setFieldsValue({
                datacenterId: data.list[0].id,
              });
              this.loadNode(data.list[0].id);
            }
          }
        }
      });
    },
    loadNode(id) {
      this.nodeList = [];
      let postData = {
        datacenterId: id,
        pageSize: 99,
      };
      if (this.isF0401) {
        this.airList = [];
        this.form.setFieldsValue({
          nodeId: "",
          airId: "",
        });
        postData.content = '查看数据中心关键设备节点传导特性拟合页面';
        postData.title = '健康智能监控-数据中心关键设备节点传导特性拟合';
      } else {
        this.form.setFieldsValue({
          nodeId: "",
        });
        postData.content = '查看基于能耗传导的数据中心运行仿真页面';
        postData.title = '健康智能监控-基于能耗传导的数据中心运行仿真';
      }
      gPostAction("/analysis/pageNodeFitter", postData).then((res) => {
        if (res.success) {
          const data = res.data;
          if (data && data.list) {
            this.nodeList = data.list;
            if (data.list && data.list.length) {
              this.form.setFieldsValue({
                nodeId: data.list[0].id,
              });
              if (this.isF0401) {
                this.loadAir(id);
              }
            }
          }
        }
      });
    },
    loadAir(id) {
      gPostAction("/analysis/pageAirFitter", {
        datacenterId: id,
        pageSize: 99,
      }).then((res) => {
        if (res.success) {
          const data = res.data;
          if (data && data.list) {
            this.airList = data.list;
            if (data.list && data.list.length) {
              this.form.setFieldsValue({
                airId: data.list[0].id,
              });
            }
          }
        }
      });
    },
    handleDatacenterChange(value) {
      this.loadNode(value);
    },
    loadData() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let param = {
            startTime: moment(values.rangeTime[0]).format("YYYY-MM-DD HH:mm:ss"),
            endTime: moment(values.rangeTime[1]).format("YYYY-MM-DD HH:mm:ss"),
            metricX: "server_power_consumption",
          };
          let postUrl = '';
          if (this.isF0401) {
            postUrl = '/analysis/doFitter';
            param.nodeId = values.nodeId;
            param.airId = values.airId;
          } else {
            postUrl = '/analysis/doSimulate';
            param.degree = values.degree;
            param.deviceId = values.nodeId;
            param.datacenterId = values.datacenterId;
          }
          gPostAction(postUrl, param).then((res) => {
            this.scatterData = [];
            this.lineData = [];
            if (res.success) {
              const charts = res.data.charts;
              if (charts) {
                charts.forEach((item) => {
                  if (item.type === "scatter") {
                    this.xlabel = item.xlabel;
                    this.ylabel = item.ylabel;
                    if (item.data) {
                      item.data.forEach((d) => {
                        this.scatterData.push([d.dataX, d.dataY]);
                      });
                    }
                  }
                  if (item.type === "line") {
                    if (item.data) {
                      item.data.forEach((d) => {
                        this.lineData.push([d.dataX, d.dataY]);
                      });
                    }
                  }
                  this.drawChart();
                });
              }
            }
          });
        }
      });
    },
    drawChart() {
      if (!(this.scatterData && this.scatterData.length)) {
        this.$message.warning("该时间区间内暂无相关数据");
      }
      let myChart = echarts.init(document.getElementById("myChart"));
      const xlabel = this.xlabel;
      const ylabel = this.ylabel;
      myChart.setOption({
        tooltip: {
          formatter: function (params, ticket, callback) {
            if (params && params.value && params.value.length) {
              return (
                xlabel +
                "：" +
                params.value[0] +
                "<br />" +
                ylabel +
                "：" +
                params.value[1]
              );
            }
          },
        },
        xAxis: {
          name: this.xlabel,
          scale: true,
        },
        yAxis: {
          name: this.ylabel,
          type: "value",
          splitLine: {
            lineStyle: {
              type: "dashed",
            },
          },
        },
        series: [
          {
            name: this.ylabel,
            type: "scatter",
            emphasis: {
              label: {
                show: false,
                position: "left",
                color: "blue",
                fontSize: 16,
              },
            },
            data: this.scatterData,
          },
          {
            name: "拟合-" + this.ylabel,
            type: "line",
            showSymbol: false,
            smooth: true,
            data: this.lineData,
            markPoint: {
              itemStyle: {
                color: "transparent",
              },
              label: {
                show: true,
                position: "left",
                color: "#333",
                fontSize: 14,
              },
              data: [
                {
                  coord: this.lineData[this.lineData.length - 1],
                },
              ],
            },
          },
        ],
      });
      setTimeout(() => {
        window.onresize = function () {
          myChart.resize();
        };
      }, 200);
    },
  },
};
</script>

<style lang="less" scoped>
.info-wrap {
  padding-bottom: 15px;
  span {
    display: inline-block;
    margin-right: 15px;
  }
}
</style>
